#!/bin/sh
#
# SrvrPowerCtrl plugin helper script for linux.
#
# This script will set the system's RTC to wake the system up in advance of a programmed SqueezeCenter alarm.
#
# If the system hardware clock is set to UTC, call this script from SrvrPowerCtrl with "/usr/local/sbin/scwakeup.sh %d".
#
# If the system hardware clock is set to local time (the default for Ubuntu 8.10 and later) then call this script
# from SrvrPowerCtrl with "/usr/local/sbin/scwakeup.sh %l".
#
#
# Copy this script to /usr/local/sbin/scwakeup.sh: cp ./scwakeup.sh /usr/local/sbin/scwakeup.sh
#
# Give root only permissions: chown root:root /usr/local/sbin/scwakeup.sh
#
# Make it executable: chmod a+x /usr/local/sbin/scwakeup.sh
#
# Test it:  sudo /usr/local/sbin/scwakeup.sh 1230493944
#
# View the log: cat /var/log/squeezecenter/srvrpowerctrl.log
#
# See http://www.mythtv.org/wiki/index.php/ACPI_Wakeup
# for apci wakeup troubleshooting...
#
#
#
#

log_file=/var/log/SBSVERSION/srvrpowerctrl.log
now_time=`/bin/date`
waketime=`/bin/date -u -d "1970-01-01 $1 seconds" +"%Y-%m-%d %H:%M:%S"`

/bin/echo "$now_time: $0 $1" >> $log_file

#Which type of RTC interface is present?

if [ -f /sys/class/rtc/rtc0/wakealarm ]; then
	#Kernels > 2.6.22 and higher use /sys/class/rtc/rtc0/wakealarm
	/bin/echo "Setting /sys/class/rtc/rtc0/wakealarm to $1 ($waketime)" >>$log_file
	/bin/echo 0 >/sys/class/rtc/rtc0/wakealarm
	/bin/echo $1 >/sys/class/rtc/rtc0/wakealarm

elif [ -f /proc/acpi/alarm ]; then
	#Kernels < 2.6.21 and lower use /proc/acpi/alarm
	#echo yyyy-mm-dd hh:mm:ss > /proc/acpi/alarm
	/bin/echo "Setting /proc/acpi/alarm to $waketime" >>$log_file
	/bin/echo $waketime >/proc/acpi/alarm
else
	/bin/echo "SrvrPowerCtrl does not support RTC wakeup on this system!" >>$log_file
fi
